package com.eascs.dubbo.api;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.brand.BrandService;
import com.eascs.admin.api.internal.StoreInfoService;
import com.eascs.admin.common.service.IO2oLoanapplyDubboService;
import com.eascs.admin.loanapplyoplog.LoanapplyOpLog;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.app.dao.PageResult;
import com.eascs.brand.controller.O2oBiscController;
import com.eascs.brand.dao.O2oBrandDao;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.form.BrandForm;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.util.StringUtil;
import com.eascs.partner.dao.JxsPartnerDao;
import com.eascs.partner.entity.DealerPartnerEntity;
import com.eascs.partner.service.JxsPartnerService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;
@Service
public class BrandServiceImpl extends O2oBiscController implements BrandService {
	
	@Reference
	SysOrgService sysOrgService;
	
	@Autowired
	O2oBrandService brandService;
	
	@Autowired
	O2oPartnerService partnerService;
	
	@Autowired
	O2oBrandDao o2oBrandDao;
	
	@Autowired
	private JxsPartnerService jxsPartnerService;
	
	@Autowired
	private JxsPartnerDao jxsPartnerDao;
	
	@Value("${web.crm.url}")
	private String crmUrl;

	@Autowired
	IO2oLoanapplyDubboService loanapplyDubboService;
	
	@Autowired
	private StoreInfoService storeInfoService;
	
	@Reference
	SequenceService sequenceService;
	

	@Override
	public String addBrand(BrandForm form) {
		ModelResult<Boolean> checkForm = checkForm(form);
		if (!checkForm.getModel()) {
			return checkForm.getErrMsg();
		}
		if (!"BRA_SRCE_OTH".equals(form.getBrandSource())  ) {
			form.setBrandSourceDes(null);
		}
		if (!"OH".equals(form.getTheIndustry())) {
			form.setReOther(null);
		}
		O2oBrandEntity entity = new O2oBrandEntity();
		BeanUtils.copyProperties(form, entity);
		entity.setCreateTime(new Date());
		entity.setHostProvinceName(sysOrgService.getOrgByIds(entity.getHostProvince()).getOrgName());
		List<ActOrgEntity> actOrgEntity = sysOrgService.getOrgChildrenByOrgId(entity.getHostProvince());
		if (actOrgEntity == null || actOrgEntity.size() != 1) {
			return "找不到经办平台，请联系管理员";
		}
		entity.setOrgId(actOrgEntity.get(0).getUnitNo());
		entity.setOrgName(actOrgEntity.get(0).getOrgName());
		boolean result = brandService.getNameAndCode(entity.getBrandName(), entity.getBrandCode());
		if (!result) {
			return "该品牌已存在";
		}
		ModelResult<Boolean> insertResult = brandService.insert(entity);
		if (insertResult.isSuccess() && !insertResult.getModel()) {
			return insertResult.getErrMsg();
		} 
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.BRAND_UPDATE_ARD, entity.getId(), "新增品牌信息");
		partnerService.saveEntityLog(log);
		return null;
	}
	
	/**
	 * check品牌类型
	 * @param entity
	 * @return
	 */
	public ModelResult<Boolean> checkForm(BrandForm entity) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		if ("BRA_SRCE_OTH".equals(entity.getBrandSource()) && StringUtils.isEmpty(entity.getBrandSourceDes())) {
			modelResult.setErrMsg("请填写品牌来源");
			modelResult.setModel(false);
			return modelResult;
		}
		if ("OH".equals(entity.getTheIndustry()) && StringUtils.isEmpty(entity.getReOther()) ) {
			modelResult.setErrMsg("请填写品牌所属行业");
			modelResult.setModel(false);
			return modelResult;			
		}
		modelResult.setModel(true);	
		return modelResult;
	}

	@Override
	public O2oBrandEntity getO2oBrand(String id) {
		return o2oBrandDao.getById(O2oBrandEntity.class, id);
	}

	@Override
	public String updateBrand(BrandForm form) {
		if (!"BRA_SRCE_OTH".equals(form.getBrandSource())  ) {
			form.setBrandSourceDes(null);
		}
		if (!"OH".equals(form.getTheIndustry())) {
			form.setReOther(null);
		}
		O2oBrandEntity entity = new O2oBrandEntity();
		BeanUtils.copyProperties(form, entity);
		entity.setUpdateTime(new Date());
		entity.setHostProvinceName(sysOrgService.getOrgByIds(entity.getHostProvince()).getOrgName());
		List<ActOrgEntity> actOrgEntity = sysOrgService.getOrgChildrenByOrgId(entity.getHostProvince());
		if (actOrgEntity == null || actOrgEntity.size() != 1) {
			return "找不到经办平台，请联系管理员";
		}
		entity.setOrgId(actOrgEntity.get(0).getUnitNo());
		entity.setOrgName(actOrgEntity.get(0).getOrgName());
		
		if (!form.getOldBrandName().equals(entity.getBrandName())) {
			boolean result = brandService.getNameAndCode(entity.getBrandName(), entity.getBrandCode());
			if (!result) {
				return "该品牌已存在";
			}
		}
		ModelResult<Boolean> updateResult = brandService.update(entity);
		if (updateResult.isSuccess() && !updateResult.getModel()) {
			return updateResult.getErrMsg();
		} 
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.BRAND_UPDATE_RD, entity.getId(), "修改品牌信息");
		partnerService.saveEntityLog(log);
		return null;
	}

	@Override
	public String startFlow(String id) {
		O2oBrandEntity o2oBrandEntity = brandService.getEntityById(id);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oBrandEntity, "startFlow");
		if (!checkRole.getModel()) {
			return checkRole.getErrMsg();
		}
		ModelResult<Boolean> startUp = brandService.startUp(id);
		if (!(startUp.isSuccess()) || !(startUp.getModel()) ) {
			return startUp.getErrMsg();
		}
		return null;
	}
	
	/**
	 * check当前用户是否为经办人
	 * @param entity
	 * @return
	 */
	public ModelResult<Boolean> isCurrentRole(O2oBrandEntity entity, String operateType) {
		ModelResult<Boolean> modelResult=new ModelResult<>();
		User user = UserHolder.getUser();
		if (!user.getNo().equals(entity.getOperatorId()) && !user.isSuperAdministrator()) {
			if ("edit".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人编辑");
			} else if ("delete".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人删除");
			} else if ("startFlow".equals(operateType)) {
				modelResult.setErrMsg("该流程只能由经办人发起");
			}
			modelResult.setModel(false);	
			return modelResult;
		}
		modelResult.setModel(true);
		return modelResult;
		
	}
	@Override
	public boolean deleteAgency(String agencyId) {
		return jxsPartnerDao.deleteJxsPartnerEntityById(agencyId);
	}

	@Override
	public String addAgency(DealerPartnerEntity param) {
		//String[] arr = param.getOrgProvinceId().split("_");
		//param.setOrgProvinceId(arr[0]);
		//param.setOrgProvince(arr[1]);
		param.setOrgProvince((sysOrgService.getOrgByIds(param.getOrgProvinceId()).getOrgName()));
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(param.getOrgProvinceId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return "找不到经办平台，请联系管理员";
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if (org.getOrgLevel() == 4)
				actOrgEntity = org;
		}
		if (actOrgEntity == null) {
			return "找不到经办平台对应的省区金融部，请联系管理员";
		}
		param.setOrgProvince(param.getOrgProvince());
		param.setOrgId(actOrgEntity.getUnitNo());
		param.setOrgName(actOrgEntity.getOrgName());

		DealerPartnerEntity result = null;
		if (StringUtils.isNotBlank(param.getId())) {
			result = jxsPartnerDao.queryJxsPartnerEntityById(param.getId());
		}
		User user = UserHolder.getUser();
		param.setUpdator(user.getCname());
		param.setUpdateDate(new Date());
		if (result != null) {
			param.setPatternCode(result.getPatternCode());
			param.setBrandId(result.getBrandId());
			param.setStatus(result.getStatus());
			param.setWfStatus(result.getWfStatus());
			param.setCreateDate(result.getCreateDate());
			param.setCreator(result.getCreator());
			int insertResult = jxsPartnerDao.updateById(param);
			if (insertResult == 0) {
				return "修改失败";
			}
			return null;
		} else {
			param.setCreator(user.getCname());
			param.setCreateDate(new Date());
			param.setStatus(JxsPartnerDao.status_normal);
			param.setWfStatus(JxsPartnerDao.wfstatus_new);
			String patternCode = sequenceService.getSeq("O2O_JXS_PARTNER_NO", 5, "JXS_HZF");
			param.setPatternCode(patternCode);
			int insertResult = jxsPartnerDao.insert(param);
			if (insertResult == 0) {
				return "新增失败";
			}
			return null;
		}
	}

	@Override
	public void editAgency(DealerPartnerEntity dealerPartnerEntity) {
		jxsPartnerDao.updateById(dealerPartnerEntity);		
	}

	@Override
	public DealerPartnerEntity getAgencyById(String agencyId) {
		return jxsPartnerDao.queryJxsPartnerEntityById(agencyId);
	}

	@Override
	public PageResult<Object[]> queryListAgency(O2oBranPage branPage) {
		return jxsPartnerDao.queryPartnerEntityByPage(branPage);
	}

	@Override
	public String startAgencyStartFlow(String agencyId) {
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerService.getEntityById(agencyId);
		ModelResult<Boolean> checkRole = isJxsCurrentRole(dealerPartnerEntity, "jxsStartFlow");
		if (!checkRole.getModel()) {
			return checkRole.getErrMsg();
		}
		if (StringUtils.isBlank(dealerPartnerEntity.getLoanId())) {
			ModelResult<Boolean> checkAttachment = partnerService.checkJxsAttachment(agencyId);
			if (!checkAttachment.isSuccess() || !checkAttachment.getModel()) {
				return checkAttachment.getErrMsg();
			}
		}
		ModelResult<Boolean> startUp = jxsPartnerService.startUp(agencyId);
		if (startUp.isSuccess() && startUp.getModel()) {
			return null;
		} else {
			return startUp.getErrMsg();
		}
	}
	
	public ModelResult<Boolean> isJxsCurrentRole(DealerPartnerEntity entity, String operateType) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		User user = UserHolder.getUser();
		if (!user.getNo().equals(entity.getOperatorId()) && !user.isSuperAdministrator()) {
			if ("edit".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人编辑");
			} else if ("delete".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人删除");
			} else if ("jxsStartFlow".equals(operateType)) {
				modelResult.setErrMsg("该流程只能由经办人发起");
			}
			modelResult.setModel(false);
			return modelResult;
		}
		modelResult.setModel(true);
		return modelResult;
	}

	@Override
	public String deleteBrand(String parameter) {
		O2oBrandEntity o2oBrandEntity = brandService.getEntityById(parameter);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oBrandEntity, "delete");
		if (!checkRole.getModel()) {
			return checkRole.getErrMsg();
		}
		if (StringUtil.isEmpty(parameter)) {
			return "参数为空，无法删除！";
		} else {
			ModelResult<Boolean> deleteResult = brandService.delete(parameter);
			if (!deleteResult.isSuccess() && !deleteResult.getModel()) {
				return deleteResult.getErrMsg();
			}
		}
		return null;
	}

	@Override
	public PageResult<Object[]> chooseLoan(String IdNum) {
		return loanapplyDubboService.getLoanapplyInfoByIdCard(IdNum);
	}

	@Override
	public String addLoanAgency(DealerPartnerEntity param, String loanapplyNo) {
		param.setLoanId(loanapplyNo);
		String licenceName = storeInfoService.getLicenceNameByLoanapplyNo(loanapplyNo);
		if (StringUtils.isBlank(licenceName)) {
			return "贷款单关联的门店营业执照为空，请联系管理员";
		}
		param.setBusinessLicenseName(licenceName);

		String provinceCode = jxsPartnerDao.getProvinceByLoan(loanapplyNo);
		if (StringUtils.isBlank(provinceCode)) {
			return "获取贷款单省区失败";
		}
		ActOrgEntity provinceOrg = null;
		List<ActOrgEntity> provinces = sysOrgService.getOrgProvince();
		for (ActOrgEntity org : provinces) {
			if (StringUtils.equalsIgnoreCase(org.getUnitCode(), provinceCode)) {
				provinceOrg = org;
				break;
			}
		}
		if (provinceOrg == null) {
			return "获取贷款单省区失败";
		}
		param.setOrgProvinceId(provinceOrg.getOrgId());
		param.setOrgProvince(provinceOrg.getOrgName());
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(provinceOrg.getOrgId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return "找不到经办平台，请联系管理员";
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if (org.getOrgLevel() == 4) {
				actOrgEntity = org;
				break;
			}
		}
		if (actOrgEntity == null) {
			return "找不到经办平台对应的省区金融部，请联系管理员";
		}
		User user = UserHolder.getUser();
		param.setOrgId(actOrgEntity.getUnitNo());
		param.setOrgName(actOrgEntity.getOrgName());
		param.setCreator(user.getCname());
		param.setCreateDate(new Date());
		param.setStatus(JxsPartnerDao.status_normal);
		param.setWfStatus(JxsPartnerDao.wfstatus_new);
		String patternCode = sequenceService.getSeq("O2O_JXS_PARTNER_NO", 5, "JXS_HZF");
		param.setPatternCode(patternCode);
		int insertResult = jxsPartnerDao.insert(param);
		if (insertResult == 0) {
			return "新增失败";
		}
		return null;
	}
}
